﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace PhysicsSimulator
{
    class CTurnableStop : CGameObject
    {
        CSprite _stopSprite = null;
        bool _isInPressed = false;
        Vector2 _position = Vector2.Zero;
        public Vector2 Position
        {
            get
            {
                return _position;
            }
            set
            {
                _position = value;
            }
        }

        Vector2 _minPosition = Vector2.Zero;
        Vector2 _maxPosition = Vector2.Zero;

        public event EventHandler Stop = null;

        public CTurnableStop(SpriteBatch spriteBatch) : base(spriteBatch)
        {

        }

        public override void Init(ContentManager contentManager)
        {
            _stopSprite = new CSprite(contentManager.Load<Texture2D>("Images/Turnable/turnable-stop"));
            base.Init(contentManager);
        }

        public override void Update(GameTimerEventArgs timer)
        {
            if (_isInPressed)
            {
                if (Stop != null)
                {
                    Stop(this, new EventArgs());
                }
            }
            base.Update(timer);
        }

        public override void Draw(GameTimerEventArgs timer)
        {
            SpriteBatch.Draw(_stopSprite.Texture, _position, null, Color.White, 0.0f, _stopSprite.Origin, 1, SpriteEffects.None, 0);
            base.Draw(timer);
        }

        public void SetLimited(Vector2 minPos, Vector2 maxPos)
        {
            _minPosition = minPos;
            _maxPosition = maxPos;
            _position = _minPosition;
        }

        public void Pressed()
        {
            _isInPressed = true;
            _position = _maxPosition;
        }

        public void ReleasePressed()
        {
            if (_isInPressed)
            {
                _isInPressed = false;
                _position = _minPosition;
            }
        }

        public void HandleTouch(Vector2 touchPoint)
        {
            Rectangle boundRect = new Rectangle();
            boundRect.X = (int)_position.X - _stopSprite.Width / 2;            
            boundRect.Y = (int)_position.Y - _stopSprite.Height / 2;
            boundRect.Width = _stopSprite.Width;
            boundRect.Height = _stopSprite.Height;

            if (touchPoint.X >= boundRect.Left && touchPoint.X <= boundRect.Right
                && touchPoint.Y >= boundRect.Top && touchPoint.Y <= boundRect.Bottom)
            {
                Pressed();
            }
        }
    }
}
